package controllers.listeners.semrep;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;

import models.FeaturesModel;
import objects.Constituent;
import objects.Feature;
import views.MainPanel;

/* Adds a new feature to the highlighted constituent */
/* actionPerformed when you click on the features table */
public class AddFeatureActionListener implements ActionListener {
	
	private MainPanel view;
	private JComboBox<String> cmbNames;
	private JComboBox<String> cmbValues;
	
	public AddFeatureActionListener() {
		view = null;
	}
	
	// TODO: Do not allow duplicates

	@Override
	public void actionPerformed(ActionEvent e) {
		String strCurrConstituent = view.getCurrentConstituent();
		
		if(strCurrConstituent != null) {
			cmbNames = new JComboBox<>();
			cmbValues = new JComboBox<>();
			
			LoadFeatureValuesItemListener listener = new LoadFeatureValuesItemListener();
			listener.setView(view);
			listener.setListener(this);
			cmbNames.addItemListener(listener);
			
			for (Constituent currentConstituent : FeaturesModel.getFeatures()) {
				if (currentConstituent.getLabel().equalsIgnoreCase(strCurrConstituent)) {
					for (Feature currentFeature : currentConstituent.getFeatures().getFeatureList()) {
						if (currentFeature.isEditable()) {
							cmbNames.addItem(currentFeature.getName());
						}
					}
				}
			}
			
			Object[] message = {  
				"Select feature name:", cmbNames,
				"Select feature value:", cmbValues
			};
			
			int option = JOptionPane.showConfirmDialog(null, message, "Add User-Defined Feature", JOptionPane.OK_CANCEL_OPTION);
			
			if (option == JOptionPane.OK_OPTION && cmbNames.getSelectedItem() != null && cmbValues.getSelectedItem() != null) {  
				boolean exists = false; 
				
				for (Feature currentFeature : view.getCurrCon().getFeatures().getFeatureList()) {
					if (currentFeature.getName().equals(cmbNames.getSelectedItem().toString())) {
						exists = true;
						break;
					}
				}
				
				if (exists) {
					JOptionPane.showMessageDialog(null, "Feature already in list.", "Warning", JOptionPane.WARNING_MESSAGE);
					return;
				}
				
				String[] newRow = {cmbNames.getSelectedItem().toString(), cmbValues.getSelectedItem().toString()};
				view.addRow(newRow);
				
				Feature newFeature = new Feature();
				newFeature.setName(cmbNames.getSelectedItem().toString());
				newFeature.setValue(cmbValues.getSelectedItem().toString());
				view.getCurrCon().getFeatures().addFeatureListItem(newFeature);
			}  
		}
	}
	
	public void setView(MainPanel view) {
		this.view = view;
	}
	
	public String getSelectedName() {
		return (String) cmbNames.getSelectedItem();
	}
	
	public JComboBox<String> getCmbValues() {
		return cmbValues;
	}
	
}
